var config = require('../../../../config');
var common = require("../../../common/common.js");
  const adrcUrl = config.adrcUrl;
  const wxpayUrl = config.wxpayUrl;
  const ntyUrl = config.ntyUrl;
  const ordUrl = config.ordUrl;
  const userdefuldUrl = config.userdefuldUrl ;
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    items: [
      { name: 'CHN', value: '货到付款（现金）', checked: 'true' },
      { name: 'USA', value: '货到付款（刷卡）' },
    ],
    showView: false,
    'num':1,
    'price':200,
    'money':200,
    'pinkage':38,
    'hesuan':202,
    'shipp':10,
    'selas':0,
    'salest':true,
    'jk':false
  },
/**
 * 显示与隐藏
 */
  onChangeShowState: function () {
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    wx.showNavigationBarLoading()
    showView: (options.showView == "true" ? true : false);
    var that=this;

    /*设置产品信息*/
    var value = wx.getStorageSync('details')
    var pin = 0;
    if (value) {
      var sem = 0;
      var salest = false;//是否
      var num = this.data.num;  ;
      if(options.num>0){
          num=options.num;
      }
     
      var money=value.money;
      pin=options.pin;
      if(pin>0){
          money = value.sepcary[pin].money;
      }
     
      var hesuan = common.activity(value.activity, num, money, 10);
      this.setData({
        details: value,
        price: value.price,
        money: money,
        pinkage: 38,
        shipp: 10,
        hesuan: hesuan['mn'],
        proid: value.id,
        selas: sem,
        salest: salest,
        act: value.activity,
        actinfo: hesuan['pro'],
        num:num,
        pin: pin,
      })
    }
    /*end设置产品信息*/
   
    /*通讯地址*/
    app.getUserOpenId(function (err, openid) {
      if (!err) {
        wx.request({
          url: userdefuldUrl + openid, //仅为示例，并非真实的接口地址  
          success:function(res){

            var int={};
            int['userName']=res.data.username;
            int['telNumber'] = res.data.telnumber;
            int['provinceName'] = res.data.provincename;
            int['cityName'] = res.data.cityname;
            int['countyName'] = res.data.countyname;
            int['detailInfo'] = res.data.detailinfo;
            
            if (res.data){
              that.setData({
                adr: int,
                adrid: res.data.id,
                ardid: res.data.id
              })
            }else{

              wx.chooseAddress({
                success: function (res) {
                  var adr = res;
                 
                      wx.request({
                        url: adrcUrl, //仅为示例，并非真实的接口地址  
                        data: {
                          userid: openid,
                          username: res.userName,
                          telnumber: res.telNumber,
                          provincename: res.provinceName,
                          cityname: res.cityName,
                          countyname: res.countyName,
                          detailinfo: res.detailInfo,
                        },
                        method: 'post',
                        header: {
                          'content-type': 'application/json'
                        },
                        success: function (res) {
                          console.log(res);
                          that.setData({
                            adr: adr,
                            adrid: res.data.id,
                          
                          })
                        }
                      })

                      wx.hideNavigationBarLoading()
                },
                fail: function (e) {
                  wx.showModal({
                    title: '收货地址提示',
                    content: '您没有填写收货地址,去填写收货地址',
                    success: function (res) {
                      if (res.confirm) {
                        wx.navigateTo({
                          url: '/pages/myinfo/site/site_add/site_add'
                        })
                      } else if (res.cancel) {

                      }
                    }
                  })
                }
              });

            }     
            wx.hideNavigationBarLoading();      
          }
        })
      }
    })
    /*end 通讯地址*/


  },
  /**
   * 点击减号数组递减
   */
  onJianHao: function () {
    var num = this.data.num;//数量
    var pinkage = this.data.pinkage;//免费运费金额
    var shipp = this.data.shipp;//运费
    var price = this.data.money;//单价
    var sales = this.data.selas;//促销活动
    var salest = this.data.salest;//是活动关的是金额
    var act = this.data.act//活动信息
    num = parseInt(num) - 1;
    var hesuan = common.activity(act, num, price, 10)
    /*
    var hesuan = price * num;
    if (hesuan < pinkage) {
      hesuan = hesuan + pinkage;
    }
    if (salest){
      hesuan = hesuan - sales;
    }*/
    
    if (num > 0){
      this.setData({
        num:num,
        hesuan: hesuan['mn'],
        actinfo: hesuan['pro'],
      })
    }
  },
  /**
   * 点击加号数组叠加
   */
onJiaHao:function(){
  var num = this.data.num;//数量
  var price = this.data.money;//单价
  var pinkage = this.data.pinkage;//免费运费金额
  var shipp = this.data.shipp;//运费
  var sales = this.data.selas;//促销活动
  var salest = this.data.salest;
  var act = this.data.act//活动信息
 
  num = parseInt(num) + 1;

  var hesuan = common.activity(act, num, price, 10)

  this.setData({
    hesuan: hesuan['mn'],
    num: num,
    actinfo: hesuan['pro'],
  })                  
},
  /**
   * 微信支付
   */
  onWeChatPay:function(){
    
    var self = this

    console.log(self.data.adrid);
    if (self.data.adrid<=0){
      wx.showModal({
        title: "收货地址提示",
        content: "没有收货地址，请填写收货地址",
        showCancel: false,
        confirmText: "确定"
      })
      return ;
    }
    self.setData({
      loading: true
    })
    // 此处需要先调用wx.login方法获取code，然后在服务端调用微信接口使用code换取下单用户的openId
    // 具体文档参考https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html?t=20161230#wxloginobject

    app.getUserOpenId(function (err, openid) {
      var paymentUrl = wxpayUrl;
      
      if (!err) {       
        wx.request({
          url: paymentUrl,  
          data: {
            openid: openid,
            proid: self.data.proid,
            ardid: self.data.adrid,
            num: self.data.num,
            pin:self.data.pin,
          },
          method:'POST',
          success: function (res) {
            var id=res.data.id;
            var payargs = res.data
            wx.requestPayment({
              timeStamp: payargs.timeStamp.toString(),
              nonceStr: payargs.nonce_str,
              package: 'prepay_id='+payargs.prepay_id,
              signType: 'MD5',
              paySign: payargs.paySign,
              success: function (res) {            
                wx.request({
                  url: ntyUrl,
                  data: {
                    id: id,                     
                  },
                  method: 'POST',
                  success: function (res) {

                  }
                })
                wx.redirectTo({
                  url: '/pages/myinfo/order/myorder/myorder'
                });
              }
              
            })
          }
        })
      } 
    })
  },
  //货到付款
  ordert:function(){
    var self = this;
    app.getUserOpenId(function (err, openid) {
      var paymentUrl = ordUrl + openid + '/' + self.data.proid + '/' + self.data.ardid + '/' + self.data.num+'/'+self.data.pin;
    
      if (!err) {
        wx.request({
          url: paymentUrl,
          success: function (res) {
            wx.redirectTo({
              url: '/pages/myinfo/order/myorder/myorder'
            })
          }
        })
      }
    });
  },
  //更换收货地址
  adrup:function(){
    var that=this;
    wx.chooseAddress({
      success: function (res) {
        var adr = res;
        console.log(adr);
        app.getUserOpenId(function (err, openid) {
          if (!err) {
            wx.request({
              url: adrcUrl, 
              data: {
                userid: openid,
                username: res.userName,
                telnumber: res.telNumber,
                provincename: res.provinceName,
                cityname: res.cityName,
                countyname: res.countyName,
                detailinfo: res.detailInfo,
              },
              method: 'post',
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                console.log(res);
                that.setData({
                  adr: adr,
                  adrid: res.data.id
                })
              }
            });
          }
        })
      },
    })
  }
 
})